﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCms.Core.Developers;
using MVCms.Core.Entities;
using MVCms.Core.Services;


namespace MVCms.Web.Controllers
{
    /// <summary>
    /// The Page Controller
    /// </summary>
    
    public class PageController : BaseController
    {
        /// <summary>
        /// The Generic Action that cater's for all pages.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //Check if you need to run setup
            if (ConfigurationManager.AppSettings["RunMigrations"] == "true")
            {
                return Redirect(SystemPage.Setup);
            }

            // if not setup, get the current page details
            var page = this.CurrentPage;

            VirtualPage filteredPage;

            if (page != null)
            {
                //check if the user has permission to view this page
                if (page.Allowed(User.Identity.Name))
                {
                    //if this is the login page, make sure to redirtect the user to home after he is authenticated
                    if (page.Url == SystemPage.Login.Url)
                    {
                        //only add returnurl if it's not already present
                        if (string.IsNullOrEmpty(Session["ReturnURL"] as string))
                            Session["ReturnURL"] = SystemPage.Home.Url;
                    }
                    filteredPage = page;
                }
                else 
                {
                    //redirect to login if the user doesn't have permission to view the page
                    Session["ReturnURL"] = page.Url;
                    return Redirect(SystemPage.Login.Url);
                }
            }
            else
            {
                // if the page is null, redirect to home page
                return Redirect(SystemPage.Home.Url);
            }

            //if the user has access to page, filter all page modules
            foreach (var module in filteredPage.Modules)
            {
                //set display mode based on permission
                module.Display = module.Allowed(User.Identity.Name);
            }

            //return the filtered page
            return View(filteredPage);
        }

        /// <summary>
        /// Saves the layout and position of modules in on the page.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveLayout(string items)
        {
            var page = this.ReferringPage;

            // check if the page contain's any modules
            if (items != null)
            {
                var modules = items.Split(','); // get all modules
                var panel = modules[0]; //get the associated panel
                int i = 0;

                //loop through modules
                foreach (var module in modules.Where(module => module.Length > 0 && module.StartsWith("li")))
                {
                    i++;
                    
                    var moduleSections = module.Split('_');
                    // extract the action
                    var action = moduleSections[moduleSections.Count() - 1];
                    //extract the controller
                    var controller = moduleSections[moduleSections.Count() - 2];
                    
                    //update the module based on it's new position
                    var pageModule = PageService.GetPageModule(PluginService.GetModule(controller, action), page);
                    pageModule.Position = i;
                    pageModule.Update();
                }
            }
            return View("Index", page);
        }

        /// <summary>
        /// Removes the module from the page.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RemoveModuleFromPage(string module)
        {
            //get the page where the module sites
            var page = this.ReferringPage;

            var moduleSections = module.Split('_');
            // extract the action
            var action = moduleSections[moduleSections.Count() - 1];
            //extract the controller
            var controller = moduleSections[moduleSections.Count() - 2];

            // remove the module from the page
            var pageModule = PageService.GetPageModule(PluginService.GetModule(controller, action), page);
            page.Modules.Remove(pageModule);
            pageModule.Update();

            // redirect back to page
            return Redirect(page.Url);
        }
    }
}
